<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        
    </style>
</head>
<body>
    <input type="text" id="username"><br>
    <input type="text" id="password"><br>
    <input type="button" value="登录" id="login">
    <input type="button" value="注册" id="register">
</body>
<script>

    $("#login").onclick = function(){
        ajax({
            url:"http://localhost:3000/login",
            data:{
                username:$("#username").value,
                password:$("#password").value
            },
            dataType:"txt"
        }).then(res=>{
            console.log(res);
        })
    }

    $("#register").onclick = function(){
        ajax({
            url:"http://localhost:3000/register",
            data:{
                username:$("#username").value,
                password:$("#password").value
            },
            method:"post",
            dataType:"txt"
        }).then(res=>{
            console.log(res);
        })
    }

    function ajax({ url, data={}, method="get", beforeSend, timeout=1000, dataType="json" } = {}){
        beforeSend && beforeSend();
        let s = "";
        for(let i in data){
            s += `${i}=${data[i]}&`;
        }
        if(method === "get"){
            url += "?" + s + "__t__=" + Date.now();
        }
        const xhr = new XMLHttpRequest();
        xhr.open(method, url);
        xhr.timeout = timeout;
        if(method === "get"){
            xhr.send();
        }else if(method === "post"){
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.send(s.slice(0, -1));
        }

        return new Promise((resolve, reject)=>{
            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4 && xhr.status === 200){
                    let d = dataType==="json" ? JSON.parse(xhr.responseText) : xhr.responseText;
                    resolve( d );
                }
                if(xhr.readyState === 4 && xhr.status !== 200){
                    reject && reject( xhr.status );
                }
            }
        })
    }
    function $(select){
        return document.querySelector(select);
    }
    
</script>
</html>